package com.huiquan.management.service;

import com.huiquan.analysis.dao.UserDao;
import com.huiquan.analysis.domain.User;
import com.huiquan.analysis.domain.UserPage;
import com.huiquan.foundation.constant.RoleID;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.management.dao.CompanyDao;
import com.huiquan.management.dao.UserManageDao;
import com.huiquan.management.domain.Company;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

@Service
public class UserManageService extends BaseService {

	@Autowired
	private UserManageDao userManageDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private UserAbilityService userAbilityService;
	@Autowired
	private CompanyDao companyDao;
	//页面大类
	public static String PAGE_CLASS_TYPE = "1";

	//页面tab类型
	public static String PAGE_TAB_TYPE = "2";


	public ModelAndView list(String keyword) {

		if (keyword != null && !keyword.isEmpty()) {
			keyword = "%" + keyword + "%";
		}
		// 获取展现用户
		List<User> displayUsers = userManageDao.retrieveDisplayList(keyword);

		// 获取隐藏用户
		List<User> hideUsers = userManageDao.retrieveHideList(keyword);

		List<UserPage> userPages = userManageDao.retrieveAllUserPageList();
		Map<String, List<String>> rolePages = new HashMap<>();
		Map<Integer, Map<String, String>> pages = new HashMap<>();
		List<String> u = new ArrayList<>();
		// 获取所有的权限
		Map<Integer, String> roleMap = RoleID.getRoleMap();
		// 所有权限的tabId对应name
		Map<String,Map<String,String>> roleTab = new HashMap<>();
		for(Map.Entry role:roleMap.entrySet()){
			// 大类
			List<UserPage> userClasses = userManageDao.retrieveByRole(role.getKey() + "",UserManageService.PAGE_CLASS_TYPE);

			Map<String,String> classMap = new HashMap<>();
			for(UserPage userClass:userClasses){
				classMap.put(userClass.getTabId(),userClass.getTabName());
			}
			roleTab.put(role.getKey()+"",classMap);
		}
		// tab名称对应tabId
		Map<String,String> tabNameAndTabId = new HashMap<>();
		for (UserPage userPage : userPages) {
			if (StringUtils.isNotBlank(userPage.getRole())) {
				if (rolePages.containsKey(userPage.getRole())) {
					u = rolePages.get(userPage.getRole());
					String[] classId = userPage.getTabId().split("_");
					if(StringUtils.isNotBlank(roleTab.get(userPage.getRole()).get(classId[0]))){
						userPage.setTabName(roleTab.get(userPage.getRole()).get(classId[0])+"/"+userPage.getTabName());
						tabNameAndTabId.put(userPage.getTabName(),userPage.getId()+"");
						u.add(userPage.getTabName());
					}
					rolePages.put(userPage.getRole(), u);
				} else {
					u = new ArrayList<>();
					String[] classId = userPage.getTabId().split("_");
					if(StringUtils.isNotBlank(roleTab.get(userPage.getRole()).get(classId[0]))){
						userPage.setTabName(roleTab.get(userPage.getRole()).get(classId[0])+"/"+userPage.getTabName());
						tabNameAndTabId.put(userPage.getTabName(),userPage.getId()+"");
						u.add(userPage.getTabName());
					}
					rolePages.put(userPage.getRole(), u);
				}
			}
			if (StringUtils.isNotBlank(userPage.getTabId()) && StringUtils.isNotBlank(userPage.getTabName())) {
				if (pages.get(Integer.parseInt(userPage.getRole())) != null) {
					pages.get(Integer.parseInt(userPage.getRole())).put(userPage.getTabId(), userPage.getTabName());
				} else {
					Map<String, String> upages = new HashMap<>();
					upages.put(userPage.getTabId(), userPage.getTabName());
					pages.put(Integer.parseInt(userPage.getRole()), upages);
				}
			}
		}
		for (User user : displayUsers) {
			user.setTabName(rolePages.get(user.getRole() + ""));
		}

		List<Company> companyList = companyDao.retrieveList();

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "姓名");

		Map<String, Object> map = new HashMap<>();
		map.put("display", displayUsers);
		map.put("rolePage", rolePages);
		map.put("userPage", pages);
		map.put("hide", hideUsers);
		map.put("roleMap", roleMap);
		map.put("tabNameAndTabId",tabNameAndTabId);
		map.put("companyList", companyList);
		map.put("showSearch", showSearch);

		return new ModelAndView("management/index", map);
	}

	public ReturnData addUser(String realName, String userName) {

		User user = new User();
		user.setRealName(realName);
		user.setUserName(userName);
		user.setParentId(2);
		user.setRole(RoleID.NONE.getId());
		userManageDao.addUser(user);

		return ReturnUtil.success();
	}

	private void checkRole(String role) throws Exception {
		// 校验权限下人数的规则
		checkRolePeopleNum(role);
	}

	private void checkRolePeopleNum(String role) throws Exception {

		List<String> cnt = userDao.getRolePeopleNum(role);
		int num = 1000000;
		if (cnt != null && cnt.size() > 0) {
			num = Integer.parseInt(cnt.get(0));
		}
		// 查询现有权限的人数
		List<String> peoNum = userDao.retrieveUsersByRole(Long.parseLong(role));
		int peopleNum = 0;
		if (peoNum != null && peoNum.size() > 0) {
			peopleNum = peoNum.size();
		}

		if (peopleNum + 1 > num) {
			throw new Exception("超过可配置上限。");
		}
	}

	public ReturnData setRole(String id, String roleStr) {
		// 在设置权限之前先要进行规则校验
		try {
			checkRole(roleStr);
		} catch (Exception e) {
			ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
			rc.setDesc("修改权限失败:" + e.getMessage());
			return ReturnUtil.fail(rc);
		}

		int role = Integer.parseInt(roleStr);
		int outsourceFlag = BaseContants.FLAG_NO;
		for (RoleID ri : RoleID.values()) {
			if (ri.getId().equals(role) && ri.isOutsourceFlag()) {
				outsourceFlag = BaseContants.FLAG_YES;
			}
		}
		userManageDao.setRoleAndOutsourceFlag(id, roleStr, outsourceFlag);

		StringBuffer retCode = new StringBuffer();

		List<UserPage> userPages = userManageDao.retrieveByRole(roleStr,UserManageService.PAGE_TAB_TYPE);
		// 大类
		List<UserPage> userClasses = userManageDao.retrieveByRole(roleStr,UserManageService.PAGE_CLASS_TYPE);

		Map<String,String> classMap = new HashMap<>();
		for(UserPage userClass:userClasses){
			classMap.put(userClass.getTabId(),userClass.getTabName());
		}
		for(UserPage userPage:userPages){
			String[] classId = userPage.getTabId().split("_");
			if(StringUtils.isNotBlank(classMap.get(classId[0]))){
				retCode.append(classMap.get(classId[0])+"/"+userPage.getTabName()).append("|").append(userPage.getId()).append(",");
			}
		}
		// 初始化该用户的能力记录
		userAbilityService.initByUserIdAndRoleId(Long.parseLong(id), role);

		Map<String, Object> map = new HashMap<>();
		map.put("outsourceFlag", outsourceFlag);
		if (retCode.length() > 0) {
			map.put("retCode", retCode.toString().substring(0, retCode.length() - 1));
		} else {
			map.put("retCode", "");
		}
		return ReturnUtil.success(map);
	}

	public ReturnData setPage(String id, String tabId) {
		userManageDao.setPage(id, tabId);
		return ReturnUtil.success();
	}

	public ReturnData setHide(String id, int hideFlag) {

		userManageDao.setHide(id, hideFlag);

		return ReturnUtil.success();
	}

	public ModelAndView userPage(User user) {
		user = userDao.retrieveObjectById(Integer.parseInt(user.getUserId() + ""));

		// 获取所有的权限
		Map<Integer, String> roleMap = RoleID.getRoleMap();
		// 要获取大类,链接大类和tab显示

		List<UserPage> userPages = getTab(user.getRole());
		Map<String, Object> map = new HashMap<>();
		map.put("tab", userPages);
		map.put("uid", user.getUserId());
		map.put("realName", user.getRealName());
		map.put("role", user.getRole());
		map.put("roleName", roleMap.get(user.getRole()));
		map.put("userName", user.getUserName());
		map.put("tabId", user.getTabId());

		return new ModelAndView("management/index", map);
	}

	private List<UserPage> getTab(int roleId) {
		// tab
		List<UserPage> userPages = userManageDao.retrieveByRole(roleId + "",UserManageService.PAGE_TAB_TYPE);

		// 大类
		List<UserPage> userClasses = userManageDao.retrieveByRole(roleId + "",UserManageService.PAGE_CLASS_TYPE);

		Map<String,String> classMap = new HashMap<>();
		for(UserPage userClass:userClasses){
			classMap.put(userClass.getTabId(),userClass.getTabName());
		}
		for(UserPage userPage:userPages){
			String[] classId = userPage.getTabId().split("_");
			if(StringUtils.isNotBlank(classMap.get(classId[0]))){
				userPage.setTabName(classMap.get(classId[0])+"/"+userPage.getTabName());
			}
		}
		return userPages;
	}

	public ReturnData setConpanyId(long id, String companyId) {

		userManageDao.updateCompany(id, companyId);
		return ReturnUtil.success();
	}
}
